package com.example.Lezedata.ui.activity.login;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.Lezedata.R;
import com.example.Lezedata.dataManager.GBUserManager;
import com.example.Lezedata.dataManager.LoginManager;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.activity.baseClass.GBBaseVc;
import com.example.Lezedata.ui.activity.person.MeVc;
import com.example.Lezedata.ui.activity.person.PersonVc;
import com.example.Lezedata.ui.customView.CGInputAndRightView;
import com.example.Lezedata.ui.customView.CGInputView;
import com.example.Lezedata.ui.fragment.commonfragment.inputTextField;
import com.example.Lezedata.ui.tabBar.GBTabBarVc;
import com.example.Lezedata.util.GBInterface;
import com.example.Lezedata.util.GBSaveData;
import com.example.Lezedata.util.GBToast;
import com.example.Lezedata.util.GBUtil;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import bid.Bid;

public class RegisterVc extends GBBaseVc {
    boolean showPsd = true;
    private TextView rightView;
    private CGInputView textField1;
    private CGInputAndRightView textField2;
    private CGInputAndRightView codeTF;
    private TextView codeRightView;
    boolean isPhoneLogin = true;
//    private inputTextField invCode;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public CharSequence title() {
        return "";
//        return getResources().getString(R.string.register);
    }

    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initView();
    }

    void initView (){
        textField1 = findViewById(R.id.mobile);
        textField1.leftView.setText("+86");
        textField1.inputView.setHint(getString(R.string.EnterMobile));
        textField1.inputView.setInputType(InputType.TYPE_CLASS_NUMBER);
        InputFilter []inputFilter = new InputFilter[]{GBUtil.limitFilter(11)};
        textField1.inputView.setFilters(inputFilter);


        textField2 = findViewById(R.id.password);
        textField2.leftView.setText(getString(R.string.Password));
        textField2.inputView.setHint(getString(R.string.EnterPassword));
        rightView = textField2.rightView;
        refreshRightView();
        rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPsd = !showPsd;
                refreshRightView();
            }
        });

        codeTF = findViewById(R.id.code);
        codeTF.leftView.setText(getString(R.string.Code));
        codeTF.inputView.setHint(getString(R.string.EnterCode));
        codeTF.inputView.setInputType(InputType.TYPE_CLASS_NUMBER);

        codeRightView = codeTF.rightView;
        refreshCodeRightView();
        FrameLayout.LayoutParams viewParams = (FrameLayout.LayoutParams) codeRightView.getLayoutParams();
        viewParams.rightMargin = GBUtil.dpTo2px(mContext,0);
        viewParams.width = GBUtil.dpTo2px(mContext,77);
        viewParams.height = GBUtil.dpTo2px(mContext,38);
        codeRightView.setLayoutParams(viewParams);
        codeRightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode(v);
            }
        });


//        invCode = (inputTextField)getSupportFragmentManager().findFragmentById(R.id.invCode);
//        invCode.mViewModel.code.setValue("邀请码");
//        invCode.mViewModel.hint.setValue("请输入邀请码(选填)");
//        invCode.viewCreatedListener = new GBInterface() {
//            @Override
//            public void onViewCreated(View view) {
//                invCode.textView_input.setInputType(InputType.TYPE_CLASS_NUMBER);
//                InputFilter []inputFilter = new InputFilter[]{GBUtil.limitFilter(11)};
//                invCode.textView_input.setFilters(inputFilter);
//            }
//        };

        findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    register();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.switchAccountType).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPhoneLogin = !isPhoneLogin;
                switchLoginType();
            }
        });

        switchLoginType();
    }

    void sendCode(View view){
        String phone = textField1.inputView.getText().toString();
        String email = phone;
        String phoneCode = textField1.leftView.getText().toString();
        if (GBUtil.stringIsEmpty(phone)){
            GBToast.shortToast(textField1.inputView.getHint().toString());
            return;
        }
        Bid.SmsType smsType = Bid.SmsType.ST_REG;
        if (!isPhoneLogin){
            phoneCode = "86";
            phone = "";
        }else {
            email = "";
        }

        hudShow();
        Bid.GetSmsCodeRequest smsCodeRequest = Bid.GetSmsCodeRequest.newBuilder()
                .setPhone(phone)
                .setEmail(email)
                .setPhoneCode(phoneCode)
                .setSmsType(Bid.SmsType.ST_REG).build();

        GBNetRequest.stub().getSmsVerificationCode(smsCodeRequest,ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.SmsCodeResponse>() {
            @Override
            public void complete(Bid.SmsCodeResponse value, GBError error) {
                hudDismiss();
                if (error == null){
                    GBToast.shortToast(isPhoneLogin?"短信发送成功！":"邮件发送成功！");
                    Date date = new Date();
                    dueTime = date.getTime()/1000 + 120;
                    codeRightView.setEnabled(false);
                    runnable.run();
                }
            }
        }));
    }

    void refreshCodeRightView(){
        codeRightView.setGravity(Gravity.CENTER);
        codeRightView.setText("获取");
        codeRightView.setTextColor(getResources().getColor(R.color.app_color_main));
        codeRightView.setTextSize(16);

//        Drawable drawable = getResources().getDrawable(R.drawable.corner_store_miancolor_19dp);
//        codeRightView.setBackground(drawable);
    }

    void refreshRightView(){
        Drawable drawable = getResources().getDrawable(!showPsd?R.drawable.login_display:R.drawable.login_hide);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        rightView.setCompoundDrawables(drawable,null,null,null);

        if (showPsd) {
            //选择状态 显示明文--设置为可见的密码
            textField2.inputView.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            //默认状态显示密码--设置文本 要一起写才能起作用  InputType.TYPE_CLASS_TEXT | 							InputType.TYPE_TEXT_VARIATION_PASSWORD
            textField2.inputView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    void register() throws NoSuchAlgorithmException {
        if (isPhoneLogin){
            registerByPhone();
        }else {
            registerByEmail();
        }
    }

    void registerByEmail(){
        String phone = textField1.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(phone)){
            GBToast.shortToast("请输入邮箱地址");
            return;
        }
        String smsCode = codeTF.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(smsCode)){
            GBToast.shortToast("请输入验证码");
            return;
        }
        String pw = textField2.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(pw)){
            GBToast.shortToast("请输入密码");
            return;
        }
//        String inv = invCode.inputText().toString();
//        if (inv == null || inv.isEmpty()){
//            inv = "";
//        }
        pw = GBUtil.getSHA256(pw);
        hudShow();
        Bid.RegisterByEmailRequest request = Bid.RegisterByEmailRequest.newBuilder()
                .setEmail(textField1.inputView.getText().toString())
                .setSmsCode(codeTF.inputView.getText().toString())
//                .setInviteCode(inv)
                .setPw(pw).build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.LoginResponse>() {
            @Override
            public void complete(Bid.LoginResponse value, GBError t) {
                hudDismiss();
                if (t == null){
                    GBUserManager.instance().userInfo = value.getUserInfo();
                    registerSuccess(value);
                }
            }
        });
        GBNetRequest.stub().registerByEmail(request,observer);
    }

    void registerByPhone(){
        String phone = textField1.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(phone)){
            GBToast.shortToast("请输入手机号码");
            return;
        }
        String smsCode = codeTF.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(smsCode)){
            GBToast.shortToast("请输入验证码");
            return;
        }
        String pw = textField2.inputView.getText().toString();
        if (GBUtil.stringIsEmpty(pw)){
            GBToast.shortToast("请输入密码");
            return;
        }
//        String inv = invCode.inputText().toString();
//        if (inv == null || inv.isEmpty()){
//            inv = "";
//        }
        pw = GBUtil.getSHA256(pw);
        hudShow();
        Bid.RegisterRequest request = Bid.RegisterRequest.newBuilder()
                .setPhoneCode(textField1.leftView.getText().toString())
                .setSmsCode(codeTF.inputView.getText().toString())
//                .setInviteCode(inv)
                .setPhone(textField1.inputView.getText().toString())
                .setPw(pw).build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.LoginResponse>() {
            @Override
            public void complete(Bid.LoginResponse value, GBError t) {
                hudDismiss();
                if (t == null){
                    GBUserManager.instance().userInfo = value.getUserInfo();
                    registerSuccess(value);
                }
            }
        });
        GBNetRequest.stub().register(request,observer);
    }

    void switchLoginType(){
        String login_phone_code = "";
        String login_phone = "";

        if (login_phone_code == ""){
            login_phone_code = "+86";
        }
        String hint = getString(R.string.EnterMobile);
        int inputType = InputType.TYPE_CLASS_NUMBER;
        int limit = 11;

        if (!isPhoneLogin){ // 邮箱
            limit = 120;
            inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
            hint = "请输入邮箱地址";
            login_phone_code = "邮箱";
        }

        Drawable drawable = getResources().getDrawable(isPhoneLogin?R.drawable.email_type:R.drawable.phone_type);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        TextView textView = findViewById(R.id.switchAccountType);
        textView.setCompoundDrawables(null,drawable,null,null);
        textView.setText(isPhoneLogin?"邮箱注册":"手机注册");

        textField1.inputView.setHint(hint);
        textField1.leftView.setText(login_phone_code);
        textField1.inputView.setText(login_phone);
        textField1.inputView.setInputType(inputType);
        InputFilter[]inputFilter = new InputFilter[]{GBUtil.limitFilter(limit)};
        textField1.inputView.setFilters(inputFilter);
    }

    void registerSuccess(Bid.LoginResponse value){
        GBUserManager.instance().setLoginData(value);
        LoginManager.instance().setLoginStatus(LoginManager.LoginStatus_login);
        finish();
        jumpActivity(GBTabBarVc.class);
    }

    private long dueTime = 0;

    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            shutdown(dueTime);
            handler.postDelayed(this, 1000);
        }
    };

    void shutdown(long time){
        Date date = new Date();
        long currentSeconds = date.getTime()/1000;
        long stime = time - currentSeconds;
        if (stime <= 0){
            stopShutDown();
        }else {
            codeRightView.setText(String.valueOf(stime));
        }
    }

    void stopShutDown(){
        codeRightView.setEnabled(true);
        codeRightView.setText("GET");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopShutDown();
    }
}